package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.common.contants.wemedia.WemediaContans;
import com.usian.utils.common.exception.CatchCustomException;
import com.usian.utils.common.exception.code.UserStatusCode;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewService;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //1.参数检查
        if (wmNewsPageReqDto == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "参数为空");
        }
        wmNewsPageReqDto.checkParam();

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNews::getUserId, uid);
        //状态
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getStatus() != null, WmNews::getStatus, wmNewsPageReqDto.getStatus());
        //关键字
        lambdaQueryWrapper.like(null != wmNewsPageReqDto.getKeyword(), WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        //频道ID
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getChannelId() != null, WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        //时间查询
//        lambdaQueryWrapper.eq(wmNewsPageReqDto.getBeginPubDate()!=null,WmNews::getCreatedTime,wmNewsPageReqDto.getBeginPubDate());
//        lambdaQueryWrapper.le(wmNewsPageReqDto.getEndPubDate()!=null,WmNews::getCreatedTime,wmNewsPageReqDto.getBeginPubDate());
        lambdaQueryWrapper.between(wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null, WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
        IPage<WmNews> iPage = this.page(new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize()), lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }


    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1.检查参数
        if (dto == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "参数为空");
        }

        WmNews wmNews = new WmNews();
        //Spring 提供的 复制属性
        BeanUtils.copyProperties(dto, wmNews);
        //前天传过来的 文章布局 0 无图文章  1 单图文章  3 多图文章 等于-1自动
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        // 转换前端传递到后端的图片  前端是数组类型 但是 数据库使用的是字符串类型中间使用,拼接
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = "";
            for (String image : dto.getImages()) {
                images += image + ",";
            }
            wmNews.setImages(images.substring(0, images.length() - 1));
        }
        //2.保存或修改文章（wm_news）
        saveWmNews(wmNews,isSubmit);
        //3.关联文章与素材的关系
        String content = dto.getContent();
        // List<Map>
        List<Map> list = JSON.parseArray(content, Map.class);
        //素材集合 获取内容中的素材
        List<String> materials =  pickUpImageUrl(list);

        //3.1 关联内容中的图片与素材的关系（wm_news_material）  必须是发布状态才能进行保存关系
//        if (WmNews.Status.SUBMIT.getCode()==isSubmit && )
        //3.2 关联封面中的图片与素材的关系,设置wm_news的type,自动（wm_news_material）
        return null;
    }


    /**
     * 提取内容中的素材路径
     * @param list
     * @return
     */
    private List<String> pickUpImageUrl(List<Map> list) {
        List<String> materials = new ArrayList<>();
        for (Map map : list) {
            if (map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)){
                materials.add((String) map.get("value"));
            }
        }
        return materials;
    }


    /**
     * 保存或者修改文章
     * @param wmNews
     * @param isSubmit
     */
    private void saveWmNews(WmNews wmNews, Short isSubmit){
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setPublishTime(new Date());
        wmNews.setEnable((short)1);
        if (wmNews.getId()==null){
            //保存
            this.save(wmNews);
        }else {
            //修改    删除素材和文章的关系
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            this.updateById(wmNews);
        }

    }
}









